import React, { useEffect, useRef, useState } from "react";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { Button, Flex } from "antd";
import "./index.scss";
import * as echarts from "echarts";

// 定义地图数据类型
type GeoFeature = {
  type: string;
  id: string;
  properties: {
    name: string;
    cp: number[];
    childNum: number;
  };
  geometry: any;
};

type GeoData = {
  type: "FeatureCollection";
  features: GeoFeature[];
};

// 记录地图层级信息
type MapLevel = {
  name: string;
  adcode: string;
  center: [number, number]; // 中心点坐标
  zoom: number; // 缩放级别
};

function Home() {
  const chartRef = useRef<HTMLDivElement>(null);
  const mapChart = useRef<echarts.ECharts | null>(null);
  const [currentLevel, setCurrentLevel] = useState<MapLevel>({
    name: "湖北省",
    adcode: "420000_full",
    center: [114.3, 30.6], // 湖北省中心点坐标
    zoom: 1.0,
  });
  const [isLoading, setIsLoading] = useState(false);
  const resizeHandler = useRef<(() => void) | null>(null);

  // 清理旧地图实例
  const clearMapInstance = () => {
    if (mapChart.current) {
      if (resizeHandler.current) {
        window.removeEventListener("resize", resizeHandler.current);
      }
      mapChart.current.dispose();
      mapChart.current = null;
    }
  };

  // 加载地图数据
  const loadMapData = (level: MapLevel) => {
    setIsLoading(true);
    setCurrentLevel(level);

    if (!chartRef.current) return;

    clearMapInstance();
    mapChart.current = echarts.init(chartRef.current);

    // 强制容器尺寸计算（解决异步加载导致的尺寸问题）
    chartRef.current.style.display = "none";
    chartRef.current.style.display = "block";

    fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${level.adcode}.json`)
      .then((response) => {
        if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
        return response.json();
      })
      .then((geoData) => {
        const echartsMapData: GeoData = {
          type: "FeatureCollection",
          features: geoData.features.map((feature: any) => ({
            type: "Feature",
            id: feature.properties.adcode,
            properties: {
              name: feature.properties.name,
              cp: feature.properties.cp,
              childNum: feature.properties.childNum,
            },
            geometry: feature.geometry,
          })),
        };

        echarts.registerMap("hubei", echartsMapData);

        // 关键配置：确保地图强制居中
        const option = {
          animation: true, // 开启动画
          animationDuration: 500, // 动画时长
          title: {
            text: level.name,
            subtext: "数据来源：阿里云",
            left: "center",
            textStyle: { color: "#333", fontSize: 18 },
          },
          tooltip: {
            trigger: "item",
            formatter: (params: any) => `<strong>${params.name}</strong>`,
          },
          visualMap: { show: false },
          toolbox: { show: true },
          series: [
            {
              name: level.name,
              type: "map",
              mapType: "hubei",
              roam: true,
              center: level.center, // 明确指定中心点
              zoom: level.zoom, // 明确指定缩放级别
              layoutCenter: ["50%", "50%"], // 强制地图居中
              layoutSize: "100%", // 使用容器大小
              label: { show: true, color: "#333" },
              itemStyle: {
                normal: { areaColor: "#f0f9ff", borderColor: "#999" },
                emphasis: { areaColor: "#73a6ff" },
                select: { areaColor: "#ffd700" },
              },
            },
          ],
        };

        // 分两步设置配置：先基础配置，再居中配置
        mapChart.current?.setOption(option);

        // 强制重绘并居中
        setTimeout(() => {
          mapChart.current?.setOption({
            series: [
              {
                center: level.center,
                zoom: level.zoom,
              },
            ],
          });
          mapChart.current?.resize();
        }, 50);

        // 管理resize事件
        resizeHandler.current = () => {
          mapChart.current?.resize();
        };
        window.addEventListener("resize", resizeHandler.current);

        // 点击事件处理
        mapChart.current?.on("click", (params: any) => {
          console.log("点击地区:", params.name);
          mapChart.current?.dispatchAction({
            type: "unselect",
            seriesIndex: 0,
          });

          const cityMapConfig: Record<string, MapLevel> = {
            宜昌市: {
              name: "宜昌市",
              adcode: "420500_full",
              center: [111.3, 30.7],
              zoom: 1.0,
            },
            武汉市: {
              name: "武汉市",
              adcode: "420100_full",
              center: [114.3, 30.6],
              zoom: 1.0,
            },
            枝江市: {
              name: "枝江市",
              adcode: "420583",
              center: [111.7, 30.4],
              zoom: 1.0,
            },
            // 可扩展更多城市...
          };

          if (params.name && cityMapConfig[params.name]) {
            const newLevel = cityMapConfig[params.name];
            // 使用 dispatchAction 实现动画过渡
            mapChart.current?.dispatchAction({
              type: "geoRoam",
              roamType: "scale",
              scale: newLevel.zoom / currentLevel.zoom,
              center: newLevel.center,
            });

            // 延迟加载新地图数据
            setTimeout(() => {
              loadMapData(newLevel);
            }, 500);
          } else {
            mapChart.current?.dispatchAction({
              type: "select",
              seriesIndex: 0,
              dataIndex: params.dataIndex,
            });
          }
        });
      })
      .catch((error) => {
        console.error("地图初始化失败:", error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  useEffect(() => {
    loadMapData({
      name: "湖北省",
      adcode: "420000_full",
      center: [114.3, 30.6],
      zoom: 1.0,
    });

    return () => {
      clearMapInstance();
    };
  }, []);

  return (
    <div className="Home">
      <div>首页</div>

      <Flex gap="middle" wrap>
        <h1 className="text-center">湖北省地图可视化</h1>

        {currentLevel.name !== "湖北省" && (
          <div className="text-center mb-3 flex-row">
            <Button
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition"
              onClick={() =>
                loadMapData({
                  name: "湖北省",
                  adcode: "420000_full",
                  center: [114.3, 30.6],
                  zoom: 1.0,
                })
              }
            >
              {/* <i className="fa fa-arrow-left mr-2"></i>返回湖北省地图 */}
              <ArrowLeftOutlined />
              返回湖北省地图
            </Button>
          </div>
        )}
      </Flex>

      {isLoading && (
        <div className="text-center py-8">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
          <p className="mt-2 text-gray-500">地图加载中...</p>
        </div>
      )}

      {/* 确保容器有明确尺寸且不使用过渡 */}
      <div
        ref={chartRef}
        id="hubeiMap"
        className={`w-full h-[500px] bg-gray-50 rounded-lg shadow-md ${
          isLoading ? "opacity-50 pointer-events-none" : ""
        }`}
        style={{ transition: "none" }}
      ></div>

      <div className="mt-4 text-center text-sm text-gray-500">
        提示：点击地区可查看详情，可缩放和平移地图
      </div>
    </div>
  );
}

export default Home;
